package Package;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.jasper.tagplugins.jstl.core.Out;
import org.xml.sax.SAXException;

/**
 * Servlet implementation class Controller
 */
@WebServlet("/Controller")
/**
 * Class Controller.
 * @author Ingrid Campos
 * @author Sandra Calderon
 * */
public class Controller extends HttpServlet {
	Validate validate=new Validate();
	FileXml xml;
	RequestDispatcher rdispatcher;
	private static final long serialVersionUID = 1L;
       
    /**
     * @throws IOException 
     * @throws SAXException 
     * @throws ParserConfigurationException 
     * @see HttpServlet#HttpServlet()
     */
    public Controller() throws ParserConfigurationException {
        super();
        xml=new FileXml();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String message="Username or Password invalid";
		String msg="Not select any file";
		String username;
		String password;
		String file="";
		String myFile="";
		
		if (request.getParameter("button").compareToIgnoreCase("SEND")==0){
			username=request.getParameter("username");
			password=request.getParameter("password");
			if(validate.readFile(username, password)){
				rdispatcher=request.getRequestDispatcher("View.jsp");
				rdispatcher.forward(request, response);
			}
			else{
				request.setAttribute("attribute", message);
				rdispatcher=request.getRequestDispatcher("Index.jsp");
				rdispatcher.forward(request, response);
			}
		}
		if (request.getParameter("button").compareToIgnoreCase("Generate XML")==0){
			try {
				file=request.getParameter("ar_dates");
				for (int i = 0; i < file.length(); i ++) {
					if (file.charAt(i)=='\\') 
						myFile = file.replace('\\','/' );
				}
				xml.read(myFile);
				xml.generateXml();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			request.setAttribute("attribute1", "<a href=C:\\Users\\Ingrid\\Documents\\eclipse-jee-helios-SR2-win32\\eclipse\\file.xml>---New XML---</a>");
			rdispatcher=request.getRequestDispatcher("View.jsp");
			rdispatcher.forward(request, response);
		}
	}
}
